package day0719.jdbc.utils;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * @author baorenfei
 * 2023/7/19  18:57
 * @description TODO
 */

public class JDBCUtilsByC3P0 {
    //创建数据源
    private static DataSource dataSource = new ComboPooledDataSource("mysql");

    //线程变量
    private static ThreadLocal<Connection> tl = new ThreadLocal<>();

    //获取连接对象的方法
    public static Connection getConn(){
        Connection conn = tl.get();
        try {
            if(conn==null || conn.isClosed()){
                conn = dataSource.getConnection();
                tl.set(conn);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }

    //关闭资源
    public static void close(Connection conn , Statement st , ResultSet rs){
        if(rs!=null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(st!=null){
            try {
                st.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(conn!=null){
            try {
                conn.close();  //归还至连接池中
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
